<template>
  <div class="server-main">
    <el-form :inline="true"
      v-model="modelData"
      class="search-form">
      <el-form-item label="本体名称"
        class="form-input">
        <el-input v-model.trim="modelData.ontologyAllName"
          clearable></el-input>
      </el-form-item>
      <el-form-item label="状态"
        class="form-input">
        <el-select v-model="modelData.ontologyAllState">
          <el-option label="全部"
            value="2"></el-option>
          <el-option label="启用"
            value="0"></el-option>
          <el-option label="禁用"
            value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          size="small"
          @click="onSubmit(1)">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">本体管理</span>
        <div>
          <el-button type="primary"
            size="small"
            @click="openCreateOntology">创建本体</el-button>
          <el-button type="primary"
            size="small"
            @click="downloadFile">下载模板</el-button>
        </div>
      </div>
      <el-table :data="tableList"
        :cell-style="{ color: '#333333' }"
        :header-cell-style="{ background: '#F3F4F7', color: '#000000' }">
        <!-- <el-table-column prop="ontologyAllId" label="ID" width="50" align="center" fixed="left"></el-table-column> -->
        <el-table-column type="index"
          label="ID"
          width="50"
          align="center"
          fixed="left"></el-table-column>
        <el-table-column prop="ontologyAllName"
          label="本体名称"
          align="center"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="ontologyAllDescribe"
          label="本体描述"
          align="center"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="ontologyCount"
          label="本体类数量"
          align="center"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="relationCount"
          label="本体关系数量"
          align="center"
          show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="createUserId" label="创建人" align="center" width="160"></el-table-column> -->
        <!-- <el-table-column prop="createTime" label="创建时间" width="200" align="center"></el-table-column> -->
        <el-table-column prop="updateUserId"
          label="更新人"
          align="center"
          width="100"></el-table-column>
        <el-table-column prop="updateTime"
          label="更新时间"
          width="200"
          align="center"></el-table-column>
        <el-table-column prop="ontologyAllState"
          label="状态"
          width="120"
          align="center">
          <template slot-scope="scope">
            <i class="little-circle-blue"
              v-if="scope.row.ontologyAllState === 0"></i>
            <i class="little-circle-red"
              v-else></i>
            <span>{{
              +scope.row.ontologyAllState === 0 ? '启用' : '禁用'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作"
          fixed="right"
          align="center"
          width="340">
          <template slot-scope="scope">
            <el-link :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="openEditOntology(scope.row)">编辑</el-link>
            <el-link v-if="!scope.row.ontologyAllState"
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="goDetail(scope.row.ontologyAllId)">建模</el-link>
            <el-link :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="changeStatus(scope.row)">{{ +scope.row.ontologyAllState === 0 ? '禁用' : '启用' }}
            </el-link>
            <el-link v-if="!scope.row.ontologyAllState"
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="uploadModel(scope.row)">导入</el-link>
            <el-link v-if="!scope.row.ontologyAllState"
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="downModel(scope.row)">导出</el-link>
            <el-link :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="handleDelect(scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background
        small
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="modelData.pageSize"
        :pager-count="7"
        :current-page="modelData.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>
    <el-dialog :title="dialogConfig[dialogType].title"
      :visible.sync="dialogFormVisible"
      @close="afterDialogClose">
      <el-form :model="modelParams"
        :rules="rules"
        ref="dialogForm"
        label-position="right"
        label-width="120px">
        <el-form-item label="本体名称:"
          prop="ontologyAllName"
          class="dialog-inline">
          <el-input maxlength="50"
            show-word-limit
            v-model.trim="modelParams.ontologyAllName"></el-input>
        </el-form-item>
        <el-form-item label="本体描述:"
          prop="ontologyAllDescribe"
          class="dialog-inline">
          <el-input type="textarea"
            maxlength="50"
            v-model.trim="modelParams.ontologyAllDescribe"
            :autosize="textSizeConfig"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary"
          @click="submitDialogForm"
          :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量导入"
      :visible.sync="uploadFormVisible"
      @close="afterDialogClose">
      <div class="upload-hint">
        请选择需要导入的本体文件，仅支持文件格式为.xls、.xlsx、.csv、.json、.rdf、.owl,.txt的文件。
      </div>
      <el-form :model="uploadParams"
        :rules="uploadRules"
        ref="uploadForm"
        label-position="right"
        label-width="120px">
        <el-form-item label="选择文件:"
          prop="fileName"
          class="dialog-inline">
          <el-input v-model="uploadParams.fileName"
            readonly>
            <template slot="append">
              <el-upload class="upload-demo"
                accept=".xls,.xlsx,.csv,.xls,.json,.xlsx,.rdf,.owl,.txt"
                :before-upload="beforeUpload"
                :show-file-list="false">
                <el-button type="primary">选择文件</el-button>
              </el-upload>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button @click="resetDialogForm">取 消</el-button>
        <el-button type="primary"
          @click="submitUploadForm"
          :loading="loading">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="导出"
      :visible.sync="downFormVisible"
      @close="afterDialogCloseDown">
      <div class="upload-hint"
        style="text-align: left">
        <span>
          当前导出
          <span style="color: #4b71eb">
            {{ downloadParams.ontologyAllName }} </span>本体数据，请选择数据导出的文件格式：
        </span>
      </div>
      <el-form :model="downloadParams"
        ref="downForm">
        <el-form-item prop="type"
          class="dialog-inline"
          :rules="[
            {
              required: true,
              message: '请选择导出文件格式',
              trigger: 'blur',
            },
          ]">
          <el-radio-group v-model="downloadParams.type">
            <el-radio label="xlsx">Excel表格wps格式</el-radio>
            <el-radio label="xls">Excel表格office格式</el-radio>
            <el-radio label="csv">CSV文件格式</el-radio>
            <el-radio label="json">JSON文件格式</el-radio>
            <el-radio label="rdf">RDF文件格式</el-radio>
            <el-radio label="owl">OWL文件格式</el-radio>
            <!-- <el-radio :label="9">备选项</el-radio> -->
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button @click="afterDialogCloseDown">取 消</el-button>
        <el-button type="primary"
          @click="submitDownloasForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { updateCookie } from '@/plugins/utils/auth'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'OntologyManagement',
  components: {},
  data: () => {
    return {
      downloadParams: {
        ontologyAllName: '',
        ontologyAllId: '',
        type: ''
      },

      downFormVisible: false,
      modelData: {
        ontologyAllName: '', // 本体名称
        ontologyAllState: '2', // 状态 0 启用，1禁用，2全部
        pageNum: 1, // 页码
        pageSize: 10 // 每页条数
      },
      tableList: [], // 本体列表
      total: 0, // 数据总条数
      loading: false,
      dialogFormVisible: false,
      uploadFormVisible: false,
      editOntologyId: null, // 编辑本体的id
      modelParams: {
        ontologyAllName: '', // 本体名称
        ontologyAllDescribe: '' // 本体描述
      },
      dialogType: 'ADD',
      dialogConfig: {
        ADD: {
          title: '创建本体',
          funcName: 'createOntology'
        },
        EDIT: {
          title: '编辑本体',
          funcName: 'editOntology'
        }
      },
      rules: {
        ontologyAllName: [
          {
            required: true,
            message: '请输入本体名称',
            trigger: 'blur'
          }
        ],
        ontologyAllDescribe: [
          {
            required: true,
            message: '请输入本体描述',
            trigger: 'blur'
          }
        ]
      },
      uploadRules: {
        fileName: [
          {
            required: true,
            message: '请选择本体文件',
            trigger: ['change', 'blur']
          }
        ]
      },
      textSizeConfig: {
        minRows: 4,
        maxRows: 10
      },
      uploadParams: {
        fileName: null
      }
    }
  },
  computed: {
    ...mapState({
      containerDom: state => state.server.containerDom
    })
  },
  created() {
    if (this.$route.query.token) {
      updateCookie('token', this.$route.query.token)
    }
    // 获取本体列表
    this.getModelList()
  },
  methods: {
    ...mapMutations({
      // save_allGraphData: "ontologyModel/save_allGraphData",
      save_ontologyAllId: 'ontologyModel/save_ontologyAllId'
    }),
    afterDialogCloseDown() {
      this.downloadParams = {
        ontologyAllName: '',
        ontologyAllId: '',
        type: ''
      }
      this.downFormVisible = false
    },
    downModel(row) {
      this.downFormVisible = true
      this.downloadParams.ontologyAllId = row.ontologyAllId
      this.downloadParams.ontologyAllName = row.ontologyAllName
    },
    // 删除
    handleDelect(row) {
      let params = {
        ontologyAllId: row.ontologyAllId
      }
      this.$confirm(
        `删除后，该本体模型及本体模型中节点关系将不再展示，且不可恢复`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$axios
            .post(this.$api.ontologyModel.xinbiaoObj.deleteOntology, params)
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success(res.data.message || '操作成功')
                this.getModelList()
                this.$store.commit('ontologyModel/save_ontologyAllId', '')
              } else {
                this.$message.warning(res.data.message)
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    submitDownloasForm() {
      this.$refs.downForm.validate(valid => {
        if (valid) {
          this.$axios({
            url: `${this.$api.ontologyModel.xinbiaoObj.exportOntology}?ontologyAllId=${this.downloadParams.ontologyAllId}&type=${this.downloadParams.type}`,
            method: 'get',
            responseType: 'blob'
          })
            .then(res => {
              let url = window.URL.createObjectURL(new Blob([res.data]), {
                type: 'charset=utf-8'
              })
              var a = document.createElement('a')
              a.style.display = 'none'
              a.href = url
              a.download = `${this.downloadParams.ontologyAllName}本体导出数据.${this.downloadParams.type}`
              document.body.appendChild(a)
              a.click()
              document.body.removeChild(a)
              window.URL.revokeObjectURL(url)
              this.downFormVisible = false
            })
            .catch(err => {})
        } else {
          return false
        }
      })
    },
    // 获取事件查询列表
    getModelList() {
      let params = this.modelData
      this.$axios
        .get(this.$api.ontologyModel.xinbiaoObj.getModelList, {
          params
        })
        .then(res => {
          let data = res.data.data
          this.tableList = data.list
          this.total = data.total
          this.modelData.pageSize = data.pageSize
          this.modelData.pageNum = data.pageNum
          this.$utils.backtop(this.containerDom)
        })
        .catch(err => {})
    },
    // 查询
    onSubmit(pageNum) {
      this.modelData.pageNum = pageNum ? pageNum : this.modelData.pageNum
      this.getModelList()
    },
    // 修改当前页码
    handleCurrentChange(page) {
      this.modelData.pageNum = page
      this.getModelList()
    },
    // 修改每页条数
    handleSizeChange(e) {
      this.modelData.pageSize = e
      this.getModelList()
    },
    // 跳转详情页
    goDetail(id) {
      this.$router.push(`/ontologyModel/ontologyManagement/edit`)
      this.save_ontologyAllId(id)
      this.$store.commit('ontologyModel/save_ontologyAllId', id)
      if (row.ontologyAllState === 1) {
        this.$store.commit(
          'ontologyModel/save_ontologyAllName',
          row.ontologyAllName
        )
      }
    },
    // 修改状态
    changeStatus(item) {
      let { ontologyAllId, ontologyAllState } = item
      let params = {
        ontologyAllId,
        ontologyAllState: +ontologyAllState === 0 ? 1 : 0
      }
      if (+ontologyAllState === 0) {
        // 点击禁用时
        this.$confirm('是否禁用当前本体?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.updateStatus(params)
            this.$store.commit('ontologyModel/save_ontologyAllId', '')
          })
          .catch(() => {})
      } else {
        this.updateStatus(params)
        this.$store.commit('ontologyModel/save_ontologyAllId', ontologyAllId)
      }
    },
    updateStatus(params) {
      this.$axios
        .post(this.$api.ontologyModel.xinbiaoObj.editOntology, params)
        .then(() => {
          this.$message.success('状态更改成功')
          this.onSubmit()
        })
        .catch(err => {
          this.$message.success('状态更改失败')
        })
    },
    // 打开编辑本体框
    openEditOntology(row) {
      let { ontologyAllId, ontologyAllName, ontologyAllDescribe } = row
      this.modelParams.ontologyAllName = ontologyAllName
      this.modelParams.ontologyAllDescribe = ontologyAllDescribe
      this.editOntologyId = ontologyAllId
      this.dialogFormVisible = true
      this.dialogType = 'EDIT'
    },
    // 模态框关闭后
    afterDialogClose() {
      this.$refs.dialogForm && this.$refs.dialogForm.resetFields()
      this.$refs.uploadForm && this.$refs.uploadForm.resetFields()
    },
    // 打开新增本体框
    openCreateOntology() {
      this.dialogType = 'ADD'
      this.dialogFormVisible = true
    },
    // 取消
    resetDialogForm() {
      this.dialogFormVisible = false
      this.uploadFormVisible = false
    },
    // 确定
    submitDialogForm() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          let func = this.dialogConfig[this.dialogType].funcName
          this[func]()
          this.dialogFormVisible = false
        } else {
          return false
        }
      })
    },
    // 创建本体
    createOntology() {
      let params = this.modelParams
      this.loading = true
      this.$axios
        .post(this.$api.ontologyModel.xinbiaoObj.createOntology, params)
        .then(res => {
          let code = res.data.code
          let ontologyAllId = res.data.data
          if (+code === 10001) {
            this.$message.warning('当前本体名称已经存在！')
            this.loading = false
            return
          }

          this.loading = false
          this.dialogFormVisible = false
          // 跳转可视化界面
          this.goDetail(ontologyAllId)
          // this.onSubmit(1);
        })
        .catch(error => {
          this.loading = false
        })
    },
    // 编辑本体
    editOntology() {
      let params = {
        ontologyAllId: this.editOntologyId,
        ...this.modelParams
      }
      this.loading = true
      this.$axios
        .post(this.$api.ontologyModel.xinbiaoObj.editOntology, params)
        .then(res => {
          let code = res.data.code
          if (+code === 10001) {
            this.$message.warning('当前本体名称已经存在！')
            this.loading = false
            return
          }
          this.$message.success('编辑成功')
          this.loading = false
          this.dialogFormVisible = false
          this.onSubmit()
        })
        .catch(error => {
          this.loading = false
        })
    },
    // 下载模板
    downloadFile() {
      this.$axios({
        url: `${this.$api.ontologyModel.xinbiaoObj.downloadModel}`,
        method: 'get',
        responseType: 'blob'
      })
        .then(res => {
          let url = window.URL.createObjectURL(new Blob([res.data]), {
            type: 'charset=utf-8'
          })
          var a = document.createElement('a')
          a.style.display = 'none'
          a.href = url
          a.download = `模板.xlsx`
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
          window.URL.revokeObjectURL(url)
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 批量导入
    uploadModel(row) {
      this.uploadFormVisible = true
      this.editOntologyId = row.ontologyAllId
    },
    beforeUpload(file) {
      this.uploadParams.fileName = file.name
      this.uploadFile = file
      return false
    },
    submitUploadForm() {
      this.loading = true
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          let params = {
            file: this.uploadFile,
            ontologyAllId: this.editOntologyId
          }
          this.$fileHttp
            .uploadFile(this.$api.ontologyModel.xuekuiObj.uploladModel, params)
            .then(res => {
              let code = res.data.code
              if (code !== 200) {
                let message = res.data.message
                this.$message.warning(message)
              }
              this.loading = false
              this.uploadFormVisible = false
              this.getModelList()
            })
        } else {
          this.loading = false
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.server-main {
  position: relative;

  .search-form {
    padding: 16px 32px;
    border-radius: 4px;
    background: #ffffff;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      /deep/ .el-input__inner {
        width: 240px;
        height: 32px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #e0e0e0;
      }
    }
  }

  .el-select {
    /deep/ .el-input__inner {
      width: 240px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #e0e0e0;
    }
  }

  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .little-circle-blue {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #55c898;
      position: relative;
      right: 4px;
      top: -2px;
    }

    .little-circle-red {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #ee5564;
      position: relative;
      right: 6px;
      top: -2px;
    }

    .page-wrapper {
      margin-top: 28px;
      display: flex;
      justify-content: flex-end;
      color: rgba(0, 0, 0, 0.65);

      .data-counter {
        font-weight: 400;
        line-height: 32px;
        margin-right: 24px;
      }

      /deep/ .btn-prev,
      /deep/ .btn-next {
        margin: 0 4px;
        min-width: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        padding: 0;
      }

      /deep/ .el-pager .number {
        min-width: 28px;
        height: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin: 0 4px;
        cursor: pointer;
      }
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  /deep/ .el-table__append-wrapper {
    padding: 10px;
  }

  .el-pagination {
    float: right;
    margin-top: 20px;

    .form-input /deep/ .el-input {
      width: 200px;
    }

    /deep/ .el-input__inner {
      height: 22px;
    }
  }

  /deep/ .el-dialog {
    width: 500px;
    border-radius: 5px;
  }

  .dialog-inline {
    /deep/ .el-form-item__content {
      // width: 100%;
    }
    /deep/ .el-radio {
      margin: 10px;
      width: 150px;
    }
    /deep/ .el-textarea__inner {
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
        Microsoft YaHei, Arial, sans-serif;
    }

    button.el-button {
      background-color: $--color-primary !important;
      color: #fff !important;
      line-height: 1.2;
    }
  }

  .upload-hint {
    font-size: 12px;
    color: #aaa;
    margin: 10px 0;
    // text-align: center;
    // line-height: 40px;
  }
}
</style>
